package Util

import (
	"bytes"
	"flag"
	"io"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/akkuman/parseConfig"
	"github.com/gin-gonic/gin"
)

//读取配置文件路径
var strFolder = flag.String("c", "config", "Set Config `strFolder`")

// 获取配置数据
func Config(value string) string {
	cache := strings.Split(value, ".")
	var key = cache[1]
	for i, v := range cache {
		if i > 1 {
			key = key + " > " + v
		}
	}

	//读取配置文件路径
	flag.Parse()
	var config = parseConfig.New(*strFolder + "/" + cache[0] + ".json")
	var text = config.Get(key).(string)
	return text
}

/*
  发送GET请求
  url:请求地址
  response:请求返回的内容
*/
func Get(url string) (response string) {
	client := http.Client{Timeout: 5 * time.Second}
	resp, err1 := client.Get(url)
	defer resp.Body.Close()
	if err1 != nil {
		return
	}

	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err2 := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err2 != nil && err2 == io.EOF {
			break
		} else if err2 != nil {
			return
		}
	}

	response = result.String()
	return
}

/*
  发送POST请求
  url:请求地址，data:POST请求提交的数据,contentType:请求体格式，如：application/json
  content:请求放回的内容
*/
func Post(url string, data string, contentType string) (content string) {
	var jsonStr []byte = []byte(data)
	// jsonStr, _ := json.Marshal(data)
	// fmt.Println(string(jsonStr))
	req, err1 := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Add("content-type", contentType+";charset=utf-8")
	if err1 != nil {
		return
	}
	defer req.Body.Close()

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err2 := client.Do(req)
	if err2 != nil {
		return
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	content = string(result)
	return
}

/*
  格式化时间戳
  timestamp: 时间戳
  返回年、月、日、小时、分钟、秒
*/
func FormatTime(value string) (int, int, int, int, int, int) {
	timestamp, _ := strconv.ParseInt(value, 10, 64)
	date := time.Unix(timestamp, 0)
	year, month, day := date.Date()
	hour, min, sec := date.Clock()
	return year, int(month), day, hour, min, sec
}

/*
  时间戳转Date
  timestamp: 时间戳
*/
func Date(value string) time.Time {
	timestamp, _ := strconv.ParseInt(value, 10, 64)
	date := time.Unix(timestamp, 0)
	return date
}

/*
  fomat response data
*/
func Response(request *gin.Context, content gin.H) {
	request.JSON(http.StatusOK, content)
}
